# plugs/uptime.py
#
#

""" uptime command .. read startup time of process with ps"""

__copyright__ = 'this file is in the public domain'

from gozerbot.generic import elapsedstring, gozerpopennocheck
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.aliases import aliases
from gozerbot.plughelp import plughelp
import os, time, re

plughelp.add('uptime', 'show uptime of the bots process')

# re to match time string
timere = re.compile("(\S+\s+\S+\s+\S+\s+\S\S:\S\S:\S\S\s+\S+)", re.M)

def handle_uptime(bot, ievent):
    """ show uptime of the bot """
    args = ['ps', '-o', 'lstart', '-p', str(os.getpid())]
    try:
        proces = gozerpopennocheck(args)
    except Exception, ex:
        ievent.reply('error running popen: %s' % str(ex))
        return
    data = proces.fromchild.readlines()
    if proces.wait():
        ievent.reply('error running ps')
        return
    if not data:
        ievent.reply("can't read start time")
        return
    result = re.search(timere, ' '.join(data))
    if result:
        starttime = time.mktime(time.strptime(result.group(1)))
    else:
        ievent.reply("can't determine start time")
        return
    ievent.reply("uptime is %s" % elapsedstring(time.time() - starttime))

cmnds.add('uptime', handle_uptime, ['USER', 'WEB'])
examples.add('uptime', 'show uptime of the bot', 'uptime')
aliases.data['up'] = 'uptime'
